package com.gitee.qdbp.jdbc.stream;

import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.jdbc.condition.DbWhere;
import com.gitee.qdbp.able.jdbc.ordering.OrderPaging;
import com.gitee.qdbp.able.jdbc.ordering.Orderings;
import com.gitee.qdbp.able.jdbc.paging.PageList;
import com.gitee.qdbp.able.jdbc.paging.Paging;
import com.gitee.qdbp.jdbc.api.CrudDao;

/**
 * 分页查询后续操作<br>
 * paging后续操作有 list|listFieldValues
 *
 * @author zhaohuihua
 * @version 20210529
 */
public class CrudOnAfterPagingStream<T> {

    protected final CrudDao<T> dao;
    protected final DbWhere where;
    protected final Orderings orderings;
    protected final Paging paging;

    CrudOnAfterPagingStream(CrudDao<T> dao, DbWhere where, Orderings orderings, Paging paging) {
        this.dao = dao;
        this.where = where;
        this.orderings = orderings;
        this.paging = paging;
    }

    /**
     * 根据条件查询实体列表<br>
     * <pre>
    List&lt;SysUser&gt; users = qdbcBoot.crudStream(SysUser.class)
        .select("id,userCode,realName") // 只查某些字段
        // .selectExclude("password") // 排除掉密码字段
        .where("userType").equals(1)
            .and("createTime").between(DateTools.addDay(now, -1), DateTools.addDay(now, +1))
            .and().subCondition((w) -> {
                w.on("userCode").like("test")
                 .or("realName").like("test");
            })
            .end()
        .orderBy("createTime desc")
        .pageBy(1, 10) // 分页查询
        .list().asPartList(); // 分页后返回的是PageList, 需要转换为普通List
     * </pre>
     * 
     * @return 列表数据
     */
    public PageList<T> list() {
        OrderPaging odpg = OrderPaging.of(paging, orderings);
        return dao.list(where, odpg);
    }

    /**
     * 根据条件分页查询某个字段的值列表<br>
     * <pre>
    List&lt;String&gt; deptCodes = qdbcBoot.crudStream(SysUser.class)
        .where("userType").equals(1)
            .and("createTime").between(DateTools.addDay(now, -1), DateTools.addDay(now, +1))
            .and().subCondition((w) -> {
                w.on("userCode").like("test")
                 .or("realName").like("test");
            })
            .end()
        .orderBy("createTime desc")
        .pageBy(1, 10) // 分页查询
        .listFieldValues("deptCode", true, String.class) // 查询部门编号, true=去重
        .asPartList();
     * </pre>
     * 
     * @param fieldName 指定字段名
     * @param distinct 是否去重
     * @param valueClazz 字段值类型
     * @return 字段的值列表
     */
    public <V> PageList<V> listFieldValues(String fieldName, boolean distinct, Class<V> valueClazz)
            throws ServiceException {
        OrderPaging odpg = OrderPaging.of(paging, orderings);
        return dao.listFieldValues(fieldName, distinct, where, odpg, valueClazz);
    }
}
